<?php

namespace Hilaoyu\LaravelExtend\Services\Auth\Controllers;

use Hilaoyu\LaravelExtend\Services\Auth\AbstractModelAuthUsers;
use Hilaoyu\LaravelExtend\Services\Auth\AuthService;
use Hilaoyu\LaravelPrivateApi\PrivateApiControllerAbstract;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class AuthServiceController extends PrivateApiControllerAbstract
{
    protected function checkGuardProvideService(){
        $guard = AuthService::GuardKey();
        return config('auth.providers.'. AuthService::GetGuardConfig($guard, 'provider') .'.provide_service');
    }

    public function register(Request $request)
    {
        try{
            if(!$this->checkGuardProvideService()){
                throw new \Exception('服务不支持');
            }
            $guard_key = AuthService::GuardKey();

            $data = $this->getRequestData();

            $data['password'] = AuthService::PasswordEn(data_get($data, 'password'),$guard_key);

            $data = AuthService::SaveUser($data,'',$guard_key,true);
            //dd($data,AuthService::GetStaticError());

            if($data){
                $encrypter = $this->getEncryptor();
                comResponse()->success('注册成功')->with($data,null,$encrypter);
            }else{
                throw new \Exception(AuthService::GetStaticError(false));
            }

        }catch (\Exception $exception){
            comResponse()->failed($exception->getMessage());
        }



        return comResponse()->json();
    }

    public function login(Request $request){
        try{
            $app = $request->route('_auth_app');
            if(!$this->checkGuardProvideService()){
                throw new \Exception('服务不支持');
            }
            $guard_key = AuthService::GuardKey();

            $data = $this->getRequestData();
            $login_type = $this->getRequestData('login_type');
            $data = Arr::only($data,[
                $login_type
            ]);
            $check_pass =false;
            if('account' == $login_type){
                $check_pass =true;
                $data['password'] =  $this->getRequestData('password');
            }

            $user = AuthService::GuardCheckCredentials($guard_key,$data,$check_pass);


            if (!$user) {
                throw new \Exception('账号不存在或密码错误');
            }

            if (!data_get($user, 'status', false)) {
                throw new \Exception('账号被禁用');
            }

            if($user){
                //记录日志
                AuthService::RecordLoginLog($guard_key,$user,null,data_get($app,'id',''));

                if($user instanceof AbstractModelAuthUsers){
                    $user->setHidden([]);
                }
                $encrypter = $this->getEncryptor();
                comResponse()->success('登录成功')->with($user,null,$encrypter);
            }else{
                throw new \Exception(AuthService::GetStaticError(false));
            }

        }catch (\Exception $exception){
            comResponse()->failed($exception->getMessage());
        }



        return comResponse()->json();
    }
    public function userGet(Request $request){
        try{
            if(!$this->checkGuardProvideService()){
                throw new \Exception('服务不支持');
            }
            $guard_key = AuthService::GuardKey();

            $credentials = $this->getRequestData();
            //dd($credentials);
            //comResponse()->withDebug($credentials,'credentials');

            $user = AuthService::LoadUser($credentials,$guard_key);


            if (!$user) {
                throw new \Exception('用户不存在');
            }

            if($user){
                if($user instanceof AbstractModelAuthUsers){
                    $user->setHidden([]);
                }
                $encrypter = $this->getEncryptor();
                comResponse()->success('获取')->with($user,null,$encrypter);
            }else{
                throw new \Exception(AuthService::GetStaticError(false));
            }

        }catch (\Exception $exception){
            comResponse()->failed($exception->getMessage());
        }



        return comResponse()->json();
    }

    public function userUpdate(Request $request){
        try{
            if(!$this->checkGuardProvideService()){
                throw new \Exception('服务不支持');
            }
            $guard_key = AuthService::GuardKey();

            $credentials = $this->getRequestData('credentials');
            $data = $this->getRequestData('data');


            //dd($credentials,$data);

            $user = AuthService::LoadUser($credentials,$guard_key);


            if (!$user) {
                throw new \Exception('用户不存在');
            }

            if($user){
                if($password = data_get($data,'password')){
                    $data['password'] = AuthService::PasswordEn($password,$guard_key);
                }else{
                    unset($data['password']);
                }
                //dd($credentials,$data);
                $user = AuthService::SaveUser($data,data_get($user,'id'),$guard_key,true);
                if(!$user){
                    throw new \Exception(AuthService::GetStaticError(false));
                }
                if($user instanceof AbstractModelAuthUsers){
                    $user->setHidden([]);
                }
                $encrypter = $this->getEncryptor();
                comResponse()->success('获取')->with($user,null,$encrypter);
            }else{
                throw new \Exception(AuthService::GetStaticError(false));
            }

        }catch (\Exception $exception){
            comResponse()->failed($exception->getMessage());
        }



        return comResponse()->json();
    }


    public function changePassword(Request $request){
        try{
            if(!$this->checkGuardProvideService()){
                throw new \Exception('服务不支持');
            }
            $guard_key = AuthService::GuardKey();

            $user_id = $this->getRequestData('user_id');
            $old_password = $this->getRequestData('old_password');
            $password = $this->getRequestData('password');

            if(!$user_id ||!$old_password || !$password){
                throw new \Exception('参数错误');
            }

            $user = AuthService::LoadUser(['id'=>$user_id],$guard_key);


            if (!$user) {
                throw new \Exception('用户不存在');
            }

            if(!$user->checkPassword($old_password)){
                comResponse()->withErrors('原密码错误','old_password');
                throw new \Exception('原密码错误');
            }
            
            $password_hash = AuthService::PasswordEn($password,$guard_key);

            $user = AuthService::SaveUser(['password'=>$password_hash],$user_id,$guard_key,false);

            if($user){
                if($user instanceof AbstractModelAuthUsers){
                    $user->setHidden([]);
                }
                $encrypter = $this->getEncryptor();
                comResponse()->success('修改成功')->with($user,null,$encrypter);
            }else{
                throw new \Exception(AuthService::GetStaticError(false));
            }

        }catch (\Exception $exception){
            comResponse()->failed($exception->getMessage());
        }



        return comResponse()->json();
    }
}
